package com.project.baseTest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class ShiroTest {
    public ShiroTest() {
        //创建安全管理器
        DefaultSecurityManager manager=new DefaultSecurityManager();
        //设置权限认证的数据来源
        manager.setRealm(new CustomRealm());
        //设置安全管理器
        SecurityUtils.setSecurityManager(manager);
        //得到主体
        Subject subject = SecurityUtils.getSubject();
        //产生用户名和密码的令牌
        UsernamePasswordToken token=new UsernamePasswordToken("tom","123");
        try {
            //登录认证
            subject.login(token);
            System.out.println("登录成功");
            //查看当前用户是否拥有manage这个角色
            System.out.println(subject.hasRole("manage"));
            //查看当前用户是否同时具有manage和product两个角色
            System.out.println(subject.hasAllRoles(List.of("manage","product")));
            //查看当前用户是否拥有指定的权限
            System.out.println(subject.isPermitted("user:create"));
            System.out.println(subject.isPermitted("user:delete"));
            //查看当前用户是否同时具有指定的权限
            System.out.println(subject.isPermittedAll("user:create","order:add"));

        }catch (UnknownAccountException e){
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e1){
            System.out.println("密码错误");
        }

    }


    public static void main(String[] args) {
        new ShiroTest();
    }
}
